<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>WebSocket Canvas Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<canvas id="canvas" style="border: 1px solid grey;"></canvas>
<script>
    const canvas = document.getElementById("canvas");
    const context = canvas.getContext("2d");

    let isDrawing = false;
    let prevX, prevY;
    let color = "#000000";
    let thickness = 3;

    const socket = new WebSocket("ws://" + window.location.host + "/canvas");

    socket.onmessage = function (event) {
        const data = JSON.parse(event.data);
        console.log("=======" + data);
        if (data.type === "draw") {
            draw(data.x, data.y, data.prevX, data.prevY, data.color, data.thickness);
        }
    };

    canvas.onmousedown = function (event) {
        isDrawing = true;
        prevX = event.offsetX;
        prevY = event.offsetY;
    };

    canvas.onmousemove = function (event) {
        if (!isDrawing) return;
        draw(event.offsetX, event.offsetY, prevX, prevY, color, thickness);
        sendDrawEvent(event.offsetX, event.offsetY, prevX, prevY, color, thickness);
        prevX = event.offsetX;
        prevY = event.offsetY;
    };

    canvas.onmouseup = function (event) {
        isDrawing = false;
    };

    function draw(x, y, prevX, prevY, color, thickness) {
        context.strokeStyle = color;
        context.lineWidth = thickness;
        context.beginPath();
        context.moveTo(prevX, prevY);
        context.lineTo(x, y);
        context.stroke();
        context.closePath();
    }

    function sendDrawEvent(x, y, prevX, prevY, color, thickness) {
        const message = JSON.stringify({
            type: "draw",
            x: x,
            y: y,
            prevX: prevX,
            prevY: prevY,
            color: color,
            thickness: thickness
        });
        socket.send(message);
    }
</script>
</body>
</html>